package cn.swust.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class UploadUtilAction extends ActionSupport{
	static SimpleDateFormat sDateFormat;
	static Random r = new Random();
	static HttpServletResponse response;
public String uploadFile() {
	System.out.println("进入了上传处理类");
	HttpServletResponse response = ServletActionContext.getResponse();
	HttpServletRequest request = ServletActionContext.getRequest();
	
	String realPath ="allproducts"; //图片路径目录
	String savePath = ServletActionContext.getServletContext().getRealPath("")+"\\"+realPath+"\\"; // 获取项目根路径
	File dir = new File(savePath);
	if(!dir.isDirectory())
	    dir.mkdir();
	
	sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式
	String nowTimeStr = sDateFormat.format(new Date()); //作为商品图片目录名称
	
	savePath = savePath +nowTimeStr+"\\"; //上传保存的路径
	realPath = realPath+"/"+nowTimeStr+"/"; //返回前台显示的相对路径
	boolean isMultipart  = ServletFileUpload.isMultipartContent(request);
    System.out.println(isMultipart+"\n");
  
	if(isMultipart) //
	{
		 	DiskFileItemFactory dff = new DiskFileItemFactory();
		    dff.setRepository(dir);
		    dff.setSizeThreshold(1024000);
		    ServletFileUpload sfu = new ServletFileUpload(dff);
		    FileItemIterator fii = null;
			try {
				fii = sfu.getItemIterator(request);
			} catch (FileUploadException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		    String title = "";   //图片标题
		    String url = "";    //图片地址
		    String fileName = "";
			String state="SUCCESS";
			try {
				System.out.println("请求信息:"+fii.next()+"\n");
			} catch (FileUploadException e1) {
				System.out.println("fii没有值");
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    try {
				while(fii.hasNext()){
				    FileItemStream fis = fii.next();
				    try{
				    	System.out.println("进入了while");
				        if(!fis.isFormField() && fis.getName().length()>0){
				        	System.out.println("进入了上传处理");
				            fileName = fis.getName();
							Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");
							Matcher matcher=reg.matcher(fileName);
							if(!matcher.find()) {
								state = "文件类型不允许！";
								break;
							}
							int randnum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数，防止图片名称重复
							String productID =sDateFormat.format(new Date())+randnum+"/"+
												fileName.substring(fileName.lastIndexOf("."),fileName.length());//产生文件名；
							
							realPath = realPath+productID; //显示相对路径
							savePath = savePath + productID;//写入的文件路径
				            System.out.println("显示路径:"+realPath+"\n存储路径："+savePath);
				            
				            BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
				            FileOutputStream a = new FileOutputStream(new File(savePath));
				            BufferedOutputStream output = new BufferedOutputStream(a);
				            Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹
				        }
				        else{
				            String fname = fis.getFieldName();
				            System.out.println("进入了飞上传");
				            if(fname.indexOf("pictitle")!=-1){
				                BufferedInputStream in = new BufferedInputStream(fis.openStream());
				                byte c [] = new byte[10];
				                int n = 0;
				                while((n=in.read(c))!=-1){
				                    title = new String(c,0,n);
				                    break;
				                }
				            }
				        }

				    }catch(Exception e){
				        e.printStackTrace();
				    }
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			title = title.replace("&", "&amp;").replace("'", "&qpos;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;");
		    try {
		    	 response.getWriter().print("{'url':'"+realPath+"','title':'"+title+"','state':'"+state+"'}");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	return Action.SUCCESS;
  }
}
